<script setup lang="ts">
  import { UploadFilled } from '@element-plus/icons-vue'
  import { computed, ref, watch } from 'vue'
  import {
    useGetGoodDetail,
    useUpdateReturnFactoryGoodInfo,
  } from '@/services/pages/return-factory/useReturnFactory'
  import { UploadFile, UploadRawFile } from 'element-plus'
  import { HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import { orderAnnexUpload } from '@/api/upload'

  const { loading, goodDetail, getGoodDetail } = useGetGoodDetail()
  const {
    loading: updateGoodInfoLoading,
    form: updateGoodInfoForm,
    update,
  } = useUpdateReturnFactoryGoodInfo()

  defineOptions({
    name: 'UpdateGoodInfoReturnFactory',
  })

  const props = defineProps({
    goodId: {
      type: String,
      required: true,
    },
    serialNumber: {
      type: Number,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 抽屉的显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 表单
  const form = ref<{ desc: string; images: Array<{ file: UploadRawFile; url: string }> }>({
    desc: '',
    images: [],
  })

  /**
   * 状态 - 用于控制显示在页面上的文本和h-status的类型
   * @param {ReturnFactoryDetailGoodList['status']} status - 状态
   */
  const statusRenderData = computed<{
    txt: string
    status: 'primary' | 'success' | 'info' | 'warning'
  }>(() => {
    if (goodDetail.value.status === 0) {
      return {
        txt: '待审核',
        status: 'warning',
      }
    }

    if (goodDetail.value.status === 1) {
      return {
        txt: '待返厂',
        status: 'warning',
      }
    }

    if (goodDetail.value.status === 2) {
      return {
        txt: '待签收',
        status: 'warning',
      }
    }

    if (goodDetail.value.status === 3) {
      return {
        txt: '待检测',
        status: 'warning',
      }
    }

    if (goodDetail.value.status === 4) {
      return {
        txt: '处理中',
        status: 'primary',
      }
    }

    if (goodDetail.value.status === 5) {
      return {
        txt: '待寄回公司',
        status: 'success',
      }
    }

    if (goodDetail.value.status === 6) {
      return {
        txt: '待公司签收',
        status: 'primary',
      }
    }

    if (goodDetail.value.status === 7) {
      return {
        txt: '已完成',
        status: 'warning',
      }
    }

    if (goodDetail.value.status === 8) {
      return {
        txt: '已取消',
        status: 'success',
      }
    }

    return {
      txt: '',
      status: 'primary',
    }
  })

  // 上传图片加载
  const uploadPictureLoading = ref(false)

  // 登记信息
  const registerInfo = computed(() => {
    const username = goodDetail.value.username || ''
    const userPhone = goodDetail.value.userPhone || ''
    const province = goodDetail.value.province || ''
    const city = goodDetail.value.city || ''
    const area = goodDetail.value.area || ''
    const address = goodDetail.value.address || ''
    return `${username} ${userPhone} ${province} ${city} ${area} ${address}`
  })

  // 处理方式
  const handleMethod = computed(() => {
    if (goodDetail.value.handleMode === 0) {
      return ''
    }

    if (goodDetail.value.handleMode === 1) {
      return '确认返厂'
    }

    return '无需返厂'
  })

  /**
   * 隐藏抽屉事件
   */
  const hideDrawer = () => {
    form.value = {
      images: [],
      desc: '',
    }
    visible.value = false
  }

  /**
   * 保存事件
   */
  const onSave = async () => {
    const uploadFile = form.value.images.filter((item) => !!item.file).map((item) => item.file)
    if (uploadFile.length > 0) {
      uploadPictureLoading.value = true
      const returnFactoryPictureUploadRes = await orderAnnexUpload(
        form.value.images.map((item) => item.file),
      )
      uploadPictureLoading.value = false
      updateGoodInfoForm.value.images = returnFactoryPictureUploadRes.data.data.rows
    } else {
      updateGoodInfoForm.value.images = form.value.images.map((item) => item.url)
    }
    updateGoodInfoForm.value.repairDescr = form.value.desc
    const res = await update(props.goodId)
    if (res.code === 20000) {
      hideDrawer()
      emits('update')
    } else {
      HMessageBox.error(res.message)
    }
  }

  /**
   * 图片上传事件
   * @param {UploadFile} file - 文件对象
   */
  const handleUploadPicture = (file: UploadFile) => {
    if (form.value.images.length >= 8) {
      HMessageBox.error(infoTip.returnFactory.detail.update_good_upload_picture_count_err)
      return
    }

    if (!file.raw.type.includes('image')) {
      HMessageBox.error(infoTip.returnFactory.detail.update_good_upload_picture_type_err)
      return
    }

    if (file.raw.size / 1024 / 1024 > 50) {
      HMessageBox.error(infoTip.returnFactory.detail.update_good_upload_picture_size_err)
      return
    }

    form.value.images.push({
      file: file.raw,
      url: URL.createObjectURL(file.raw),
    })
  }

  /**
   * 移除图片事件
   * @param {Number} index - 图片索引
   */
  const handleRemovePicture = (index: number) => {
    form.value.images.splice(index, 1)
  }

  watch(
    visible,
    async (value) => {
      if (value) {
        await getGoodDetail(props.goodId)
        form.value.desc = goodDetail.value.descr
        if (goodDetail.value.images) {
          form.value.images = goodDetail.value.images.map((item) => {
            return {
              file: null,
              url: item,
            }
          })
        }
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-drawer
    v-model="visible"
    title="设备详情（可编辑）"
    :width="800"
    unit="px"
    :loading="loading || updateGoodInfoLoading || uploadPictureLoading"
  >
    <el-form class="modal_form_content" inline-message label-position="top" :model="form">
      <!-- 序号 -->
      <el-form-item label="序号">
        <el-input disabled :model-value="props.serialNumber" />
      </el-form-item>

      <!-- 序列号（序列号） -->
      <el-form-item label="序列号（序列号）">
        <el-input disabled :model-value="goodDetail.code" />
      </el-form-item>

      <!-- 状态 -->
      <el-form-item label="状态">
        <el-input disabled :model-value="statusRenderData.txt" />
      </el-form-item>

      <!-- 设备类型 -->
      <el-form-item label="设备类型">
        <el-input disabled :model-value="goodDetail.type === 1 ? '成品' : '物料'" />
      </el-form-item>

      <!-- 设备名称 -->
      <el-form-item label="设备名称">
        <el-input disabled :model-value="goodDetail.goodsName" />
      </el-form-item>

      <!-- 规格 -->
      <el-form-item label="规格">
        <el-input disabled :model-value="goodDetail.goodsSpec" />
      </el-form-item>

      <!-- 数量 -->
      <el-form-item label="数量">
        <el-input disabled :model-value="goodDetail.qty" />
      </el-form-item>

      <!-- 质保开始 -->
      <el-form-item label="质保开始">
        <el-input disabled :model-value="goodDetail.warrantyStartTime" />
      </el-form-item>

      <!-- 质保结束 -->
      <el-form-item label="质保结束">
        <el-input disabled :model-value="goodDetail.warrantyEndTime" />
      </el-form-item>

      <!-- 登记信息 -->
      <el-form-item label="登记信息">
        <el-input disabled :model-value="registerInfo" />
      </el-form-item>

      <!-- 返厂描述 -->
      <el-form-item label="返厂描述" prop="desc">
        <el-input
          v-model.trim="form.desc"
          type="textarea"
          resize="both"
          maxlength="200"
          placeholder="请输入返厂描述"
          :disabled="[7, 8].includes(goodDetail.status)"
          show-word-limit
        />
      </el-form-item>

      <!-- 返厂图片 -->
      <el-form-item label="返厂图片">
        <el-upload
          :auto-upload="false"
          :show-file-list="false"
          accept="image/*"
          action="#"
          drag
          multiple
          class="upload"
          :disabled="[7, 8].includes(goodDetail.status)"
          :on-change="handleUploadPicture"
        >
          <el-icon size="32" color="#606266">
            <UploadFilled />
          </el-icon>
          <div class="text">请上传图片（最多可上传8张）</div>
        </el-upload>
        <div class="file-list">
          <h-image
            v-for="(picture, index) in form.images"
            :key="index"
            :padding="2"
            :height="37.5"
            :width="60"
            :src="picture.url"
            :initial-index="index"
            :preview-src-list="form.images.map((item) => item.url)"
            @del="handleRemovePicture(index)"
          />
        </div>
      </el-form-item>

      <!-- 处理方式 -->
      <el-form-item label="处理方式">
        <el-input disabled :model-value="handleMethod" />
      </el-form-item>

      <!-- 处理意见 -->
      <el-form-item label="处理意见">
        <el-input disabled :model-value="goodDetail.handleOpinion" />
      </el-form-item>

      <!-- 物料单号 -->
      <!-- 先隐藏，后面会用到 -->
      <!-- <el-form-item label="物料单号"></el-form-item> -->

      <!-- 检测单号 -->
      <el-form-item label="检测单号">
        <el-input disabled :model-value="goodDetail.repairCheckNo" />
      </el-form-item>

      <!-- 检测结果 -->
      <!-- 先隐藏，后面会用到 -->
      <!-- <el-form-item label="检测结果"></el-form-item> -->

      <!-- 寄回物流名称 -->
      <el-form-item label="寄回物流名称">
        <el-input disabled :model-value="goodDetail.sendBackLogisticsName" />
      </el-form-item>

      <!-- 寄回物流单号 -->
      <el-form-item label="寄回物流单号">
        <el-input disabled :model-value="goodDetail.sendBackLogisticsNo" />
      </el-form-item>

      <!-- 寄出物流名称 -->
      <el-form-item label="寄出物流名称">
        <el-input disabled :model-value="goodDetail.sendOutLogisticsName" />
      </el-form-item>

      <!-- 寄出物流单号 -->
      <el-form-item label="寄出物流单号">
        <el-input disabled :model-value="goodDetail.sendOutLogisticsNo" />
      </el-form-item>
    </el-form>
    <template #footer>
      <h-button
        is-modal
        type="primary"
        :disabled="[7, 8].includes(goodDetail.status)"
        @click="onSave"
        >保存</h-button
      >
      <h-button is-modal @click="hideDrawer">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .upload {
    width: 100%;
    height: 75px;

    :deep(.el-upload) {
      width: 100%;
      height: 100%;

      .el-upload-dragger {
        padding: 0;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .text {
          line-height: 16px;
          height: 16px;
          color: #606266;
        }
      }
    }
  }

  .file-list {
    width: 100%;
    margin-top: 8px;
    display: grid;
    grid-template-columns: repeat(8, 60px);
    justify-content: space-between;
    row-gap: 5px;
  }

  :deep(.el-textarea) {
    width: 100%;

    .el-textarea__inner {
      width: 100% !important;
      min-height: 75px !important;
      max-height: 150px !important;
    }
  }
</style>
